#include "degfx/bitmap.h"
#include <assert.h>

#define MX__CLIP_HLINE(rect, xa, ya, xb)                                       \
   (((ya) < (rect).y1) ||                                                    \
    ((ya) > (rect).y2) ||                                                    \
    (((xb) = MX_MIN((xb), ((rect).x2))) < ((xa) = MX_MAX((xa), ((rect).x1)))))

void mx__fasthline(MX_BITMAP * bitmap, int x1, int y1, int x2, MX_PIXEL color)
{
	const unsigned int trans = MXT(color);

	if (trans == 0xFF)
		return;

	else {
		const MX_RECT *area = MXRECT(bitmap);
		MX_PIXEL *start = &bitmap->_array[(y1 - area->y1) * bitmap->_pitch + (x1 - area->x1)];
		const MX_PIXEL *end = start + (x2 - x1);
		int count = end - start + 1;

		if (trans) {
			while (count--) {
				*start = MXBLENDT(color, *start, trans);
				++start;
			}
		} else {
			while (count--)
				*start++ = color;
		}
	}
}

void mx_bitmap_hline(MX_BITMAP * bitmap, int x1, int y1, int x2, MX_PIXEL color)
{
#ifdef MXDEBUG
	const MX_RECT *area;
#endif

	if (MX__CLIP_HLINE(bitmap->_clip, x1, y1, x2))
		return;

#ifdef MXDEBUG
	area = MXRECT(bitmap);
	assert(x1 >= area->x1);
	assert(y1 >= area->y1);
	assert(x2 >= area->x1);
	assert(x1 <= area->x2);
	assert(y1 <= area->y2);
	assert(x2 <= area->x2);
#endif

	mx__fasthline(bitmap, x1, y1, x2, color);
}
